<template>
  <div style="display: flex">
    <el-col :span="1.5">
    </el-col>
    <div style="padding: 10px; width: 100%">
      <el-card shadow="hover" style="margin-bottom: 10px; padding-bottom: -5px">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5" >
            <el-form-item label="树名称" prop="dictLabel">
              <el-input v-model="queryParams.dictLabel" placeholder="请输入树名称" clearable style="width: 200px" @keyup.enter="handleQuery" />
            </el-form-item>

          </el-col>
          <el-col :span="1.5" >
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll" style="margin-left: 50px">展开/折叠</el-button>
            <el-button type="primary" plain icon="Plus" @click="treeHandleAdd" v-hasPermi="['system:dict:add']">新增顶级或其他</el-button>
          </el-col>
        </el-row>
      </el-card>
      <el-table
        :data="treeDataList"
        style="width: 100%; margin-bottom: 20px"
        row-key="dictCode"
        :default-expand-all="isExpandAll"
        ref="deptTableRef"
      >
        <el-table-column prop="dictLabel" label="树名称" sortable />
        <el-table-column prop="dictValue" label="字典值" sortable width="350px" />
        <el-table-column prop="createTime" label="创建时间" sortable width="300px"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="350px" >
        <template #default="scope">
          <el-tooltip content="新增" placement="top">
            <el-button link type="primary" icon="Plus" @click="treeHandleAdd(scope.row)" v-hasPermi="['system:dict:add']" />
          </el-tooltip>
          <el-tooltip content="修改" placement="top">
            <el-button link type="primary" icon="Edit" @click="treeHandleUpdate(scope.row)" v-hasPermi="['system:dict:edit']" />
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button link type="primary" icon="Delete" @click="treeHandleDelete(scope.row)" v-hasPermi="['system:dict:remove']" />
          </el-tooltip>
        </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加或修改测试树对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="dataFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="父级">
          <el-tree-select
            v-model="fatherLabel"
            :data="treeDataList"
            :props="{ value: 'dictValue', label: 'dictLabel', children: 'children' }"
            value-key="dictValue"
            placeholder="请选择父级，或留白新增顶级项"
            check-strictly
            :disabled="disableSel"
            @change="handleChange"
            style="width: 240px"
            clearable
          />
        </el-form-item>
        <el-form-item label="树名称">
          <el-input v-model="form.dictLabel" placeholder="请输入label" />
        </el-form-item>
        <el-form-item label="字典值" v-if="form.dictValue">
          <el-input :disabled="disableSel" v-model="v" placeholder="请输入字典值后两位" maxlength="2" oninput="value=value.replace(/[^a-zA-Z\d]/g, '')">
            <template #prepend>{{ form.dictValue }}</template>
          </el-input>
        </el-form-item>
        <el-form-item label="字典值" v-if="!form.dictValue">
          <el-input :disabled="disableSel" v-model="v" placeholder="请输入字典值"  maxlength="2" oninput="value=value.replace(/[^a-zA-Z\d]/g, '')"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="treeSubmitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="DictTree" lang="ts">
import useDictStore from '@/store/modules/dict'
import {addData, delData, getData, getDicts, updateData} from "@/api/system/dict/data";
import {DictDataForm, DictDataQuery, DictDataVO} from "@/api/system/dict/data/types";
import {DeptVO} from "@/api/system/dept/types";
import {TreeTT} from "@/api/demo/tree/types";
import {ref, watch} from 'vue'
import {handleTree2} from "@/utils/ruoyi";

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const route = useRoute();

const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const defaultDictType = ref("");

const dataFormRef = ref<ElFormInstance>();
const queryFormRef = ref<ElFormInstance>();

let fatherLabel = ref<any>('')

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const initFormData: DictDataForm = {
  dictCode: undefined,
  dictLabel: '',
  dictValue: '',
  cssClass: '',
  listClass: "default",
  dictSort: 0,
  remark: '',
  dictType: ''
}
let data = reactive<PageData<DictDataForm, DictDataQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    dictName: '',
    dictType: '',
    dictLabel: ''
  },
  rules: {
    dictLabel: [{ required: true, message: "数据标签不能为空", trigger: "blur" }],
    dictValue: [{ required: true, message: "数据键值不能为空", trigger: "blur" }],
    dictSort: [{ required: true, message: "数据顺序不能为空", trigger: "blur" }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 取消按钮 */
const cancel = () => {
  dialog.visible = false;
  reset();
}
/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  dataFormRef.value?.resetFields();
  v.value = ''
  fatherLabel.value = ''
}
/** 搜索按钮操作 */
const handleQuery = () => {
  if (treeDataList.value){
    queryParams.value.pageNum = 1
    let treeSearch: typeof treeDataList = [];
    const value = findDictLabel(treeDataList.value, queryParams.value.dictLabel).dictValue
    if (value){
      treeDataList.value = searchLabel(treeSearch, treeDataList.value, value)
    }else{
      proxy?.$modal.msgWarning("未找到该树")
    }
  }
  // console.log('treeDataList',treeDataList.value)
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.dictType = defaultDictType.value;
  queryParams.value.dictLabel = '';
  getTreeList();
}


const treeDataList = ref<any>([]);
const routeDictType = String(route.query.dictType)
let addDelete = 0;//有过增删后需要重新从后台获取新的数据，不用缓存的数据

/** 获取树数据 */
async function getTreeList() {
  let res: any;
  const treeData = useDictStore().getDict(routeDictType)
  if (addDelete != 0 || !treeData){
    res = await getDicts(routeDictType)
    res = res.data
    useDictStore().removeDict(routeDictType)
    useDictStore().setDict(routeDictType,res)
  }else{
    res = toRaw(treeData)
  }
  treeDataList.value  = proxy?.handleTree2<TreeTT>(res)
  addDelete = 0
  // console.log("treeDataList:",toRaw(treeDataList.value))
}

const v = ref<any>('')
let disableSel = ref<any>(false)
/** 新增 */
const treeHandleAdd = (row?: DictDataVO) => {
  updataVal.value = ''
  reset();
  if (row && row.dictLabel) {
    form.value.dictValue = row.dictValue;
    fatherLabel.value = row?.dictLabel
  } else {
    form.value.dictLabel = '';
    form.value.dictValue = '';
  }
  disableSel = false
  dialog.visible = true;
  dialog.title = "添加数据";
  row?.dictSort ? form.value.dictSort = row?.dictSort+1 : form.value.dictSort = treeDataList.value.length;
}
/** 删除 */
const treeHandleDelete = async (row?: DictDataVO) => {
  // 判断有无子数据，有的话就不让删
  const res = findDictLabel(treeDataList.value, row?.dictValue)
  if (res.children.length === 0){
    addDelete = 1;
    const dictCodes = row?.dictCode || ids.value;
    await proxy?.$modal.confirm('是否确认删除字典值为"' + row?.dictValue + '"的数据项？');
    await delData(dictCodes);
    await getTreeList();
    proxy?.$modal.msgSuccess("删除成功");
    useDictStore().removeDict(queryParams.value.dictType);
  }else {
    proxy?.$modal.msgWarning('此项数据含有子数据，无法删除');
  }
}
/** 修改 */
let updataVal = ref<any>('')
const treeHandleUpdate = async (row?: DictDataVO) => {
  updataVal.value  =row?.dictValue
  // 判断有无子数据，有的话就不让修改
  const req = findDictLabel(treeDataList.value, row?.dictValue)
  disableSel = req.children.length !> 0;

  reset();
  const dictCode = row?.dictCode || ids.value[0];
  const res = await getData(dictCode);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改数据";
  fatherLabel.value = row?.dictLabel

  if (row) {
    form.value.dictValue = row.dictValue.substring(0, row.dictValue.length - 2)
    v.value = row.dictValue.substring(row.dictValue.length - 2, row.dictValue.length)
  }
}
/** 提交 */
const treeSubmitForm = () => {
  const res = findDictLabel(treeDataList.value,form.value.dictValue+v.value)
  if (!res){
    if (!isNaN(Number(v.value)) || /^[A-Za-z]+$/.test(v.value)){
      form.value.dictType = routeDictType
      addDelete = 1;
      if (v.value != ''){
        form.value.dictValue += v.value
      }else {
        proxy?.$modal.msgWarning("字典值不能为空")
        return
      }
      dataFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
          form.value.dictCode ? await updateData(form.value) : await addData(form.value);
          dialog.visible = false;
          useDictStore().removeDict(queryParams.value.dictType);
          proxy?.$modal.msgSuccess("操作成功");
          await getTreeList();
        }
      });
    }else {
      proxy?.$modal.msgWarning("字典值请输入同类型字符")
    }
  }else {
    proxy?.$modal.msgWarning("同级下字典值不能重复")
  }
}

/** 修改或者新增时获取当前选中行的值 */
function handleChange(val: any){
  if (updataVal.value === val){
    proxy?.$modal.msgWarning('自身不可作为父类，请选择其他父类')
    return
  }else {
    form.value.dictValue = val
    if (isNaN(parseInt(v.value))){
      v.value = ''
    }
  }
}

/** value label 互查 */
function findDictLabel(tree: any , value: any):any {
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.dictValue === value) {
      return node;
    }else{
      if (node.dictLabel === value) {
      return node;
    }}
    if (node.children && node.children.length > 0) {
      const result = findDictLabel(node.children, value);
      if (result) {
        return result;
      }
    }
  }
  return null;
}

/** 搜索按钮 */
function searchLabel(treeSearch: any, tree: any , value: any):any {
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (value.includes(node.dictValue) || node.dictValue.includes(value)) {
      treeSearch.push(node)
    }
    if (node.children && node.children.length > 0) {
      searchLabel(treeSearch, node.children, value);
    }
  }
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children && node.children.length > 0) {
      node.children = []
    }
  }
  return handleTree2(treeSearch);
}

watch([queryParams.value, fatherLabel, v.value, form.value],(value)=>{
  if (value[0].dictLabel){
    handleQuery()
  }
  if (!value[0].dictLabel){
    getTreeList()
  }
  if (!value[1] || !isNaN(Number(value[2]))){
    form.value.dictLabel = ''
    form.value.dictValue = ''
    v.value = ''
  }
})

const isExpandAll = ref(true)
const deptTableRef = ref<ElTableInstance>();
/** 展开/折叠操作 */
function handleToggleExpandAll(){
  isExpandAll.value = !isExpandAll.value;
  toggleExpandAll(treeDataList.value, isExpandAll.value)
}
/** 展开/折叠所有 */
function toggleExpandAll(data: DeptVO[], status: boolean){
  data.forEach((item) => {
    deptTableRef.value?.toggleRowExpansion(item, status)
    if (item.children && item.children.length > 0) toggleExpandAll(item.children, status)
  })
}


onMounted(() => {
  getTreeList();
})
</script>
